package controller

import (
	"shortlink/forms"
	"shortlink/service"
	"shortlink/tools"

	"github.com/astaxie/beego"
	_ "github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
)

type LinkController struct {
	beego.Controller
}

func (c *LinkController) Edit() {

	if c.Ctx.Input.IsPost() {
		var form forms.LinkForm
		c.ParseForm(&form)
		service.UpdateLink(form.ID, c.Ctx.Input.Host(), form.Longlink)
		c.Redirect("/link/query", 302)
		return
	}
	var id int64
	c.Ctx.Input.Bind(&id, "id")
	c.Data["id"] = id
	c.Data["links"] = service.GetLink(id)
	c.TplName = "edit.html"
	// c.Redirect("/link/query", 302)
}

func (c *LinkController) Delete() {
	var id int64
	c.Ctx.Input.Bind(&id, "id")
	service.DelLink(id)
	c.Redirect("/link/query", 302)

}

func (c *LinkController) Query() {
	if c.Ctx.Input.IsGet() {

		c.Data["links"] = service.GetLinks()
		c.TplName = "link.html"
	}
}

func (c *LinkController) Add() {
	if c.Ctx.Input.IsGet() {
		c.TplName = "add.html"
		return
	} else if c.Ctx.Input.IsPost() {
		var form forms.LinkForm
		c.ParseForm(&form)
		slink := tools.CreateRandomString(6)
		service.AddLink(c.Ctx.Input.Host(), slink, form.Longlink)
		c.Redirect("/link/query", 302)
		return
	}
	c.Redirect("/link/query", 302)

}

func RedirectLongLink(c *context.Context) {
	slink := c.Input.Param(":link")
	if len(slink) > 6 {
		return
	}
	longlink := service.GetLongLink(c.Input.Param(":link"))

	c.Redirect(302, longlink)
}

func RedirectQuery(c *context.Context) {
	c.Redirect(302, "/link/query")
}
